<?php
/**
 * TimoPHP a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://www.TimoPHP.com/
 * Since: 2016
 */

namespace Timo\Core;


class Config
{
    /**
     * @var array
     */
    public $data;

    /**
     * @var \Timo\Core\Config
     */
    private static $instance;

    /**
     * 读取配置
     *
     * @param string $file 配置文件绝对路径
     */
    public function __construct($file)
    {
        $this->data = require $file;
    }

    /**
     * 实例化配置类
     *
     * @param $file
     * @param string $alias 笔名
     * @return Config
     */
    public static function load($file, $alias = '')
    {
        $alias = !empty($alias) ? $alias : $file;
        if (!isset(static::$instance[$alias])) {
            static::$instance[$alias] = new Config($file);
        }

        return static::$instance[$alias];
    }

    /**
     * 获取配置项
     *
     * @param $index
     * @param string $options
     * @return array|bool
     */
    public function get($index, $options = '')
    {
        if (isset($this->data[$index])) {
            if ($options) {
                if (is_array($options)) {
                    $result = array();
                    foreach ($options as $n) {
                        if (isset($this->data[$index][$n])) {
                            $result[$n] = $this->data[$index][$n];
                        }
                    }
                    return $result;
                } elseif (isset($this->data[$index][$options])) {
                    return $this->data[$index][$options];
                }

                return false;
            }

            return $this->data[$index];
        }
        return false;
    }

    /**
     * 设定配置项的值
     *
     * @param string $index
     * @param array|string $values
     * @return bool
     */
    public function set($index, $values = '')
    {
        if (is_array($values)) {
            if (isset($this->data[$index])) {
                $this->data[$index] = array_merge($this->data[$index], $values);
            } else {
                $this->data[$index] = $values;
            }
        } else {
            $this->data[$index] = $values;
        }

        return true;
    }

    /**
     * 合并运行时定义的配置
     *
     * @param array $append_config
     * @return $this
     */
    public function parse(array $append_config = array())
    {
        if (!empty($append_config)) {
            foreach ($append_config as $key => $value) {
                if (isset($this->data[$key]) && is_array($this->data[$key]) && is_array($value)) {
                    $this->data[$key] = array_merge($this->data[$key], $value);
                } else {
                    $this->data[$key] = $value;
                }
            }
        }

        return $this;
    }
}
